import random

from django.shortcuts import render
from django.views import View
from redis import Redis

from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.http import HttpResponse, JsonResponse
from celery_tasks.sms.tasks import send_sms_code


# Create your views here.
from utils.smsuntils import SmsUtil

# 图形验证码
class ImageCodeView(View):
    def get(self,request,uuid):
        text, image = captcha.generate_captcha()

        redis = get_redis_connection('code')
        redis.setex(uuid, 300, text)

        return HttpResponse(image, content_type='image/jepg')

# 短信验证码
class SmsView(View):
    def get(self, request, mobile):
        # 检验手机格式是否正确
        if not mobile:
            return JsonResponse({'code': 300, 'errmsg': "手机号为空"})
        # 获取用户发过来的图片验证码
        image_code: str = request.GET.get('image_code')
        print('image_code', image_code)
        image_code_uuid = request.GET.get('image_code_id')

        try:
            # 获取保存在redis里面的图片验证码
            redis: Redis = get_redis_connection('code')
            print(redis)
            image_code_redis = redis.get(image_code_uuid)
            if not image_code_redis:
                return JsonResponse({'code': 400, 'errmsg': "验证码过期"})

            image_code_redis = image_code_redis.decode()
            print('image_code_redis', image_code_redis)

            if image_code.lower() != image_code_redis.lower():
                return JsonResponse({'code': 500, 'errmsg': "图片验证码过期了"})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 600, 'errmsg': "网络异常"})

        print("发送短信给", mobile)

        flag_send = redis.get('flag_%s' % mobile )
        print('flag_send',flag_send)

        if flag_send:
            return JsonResponse({'code': 110, 'errmsg': '短信已经发送，请稍后再试'})


        # # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print('sms_code',sms_code)

        # SmsUtil().send_message(mobile=mobile, code=sms_code)
        send_sms_code.delay(mobile=mobile, code=sms_code)

        pl = redis.pipeline()

        pl.setex("smscode_%s" % mobile, 60 * 3, sms_code)
        pl.setex('flag_%s' % mobile, 120, 1)

        pl.execute()


        return JsonResponse({'code': 0, 'errmsg': "ok"})


